<template>
	<view class="message-list-page">
		<view class="message-list-page__header">
			<text class="message-list-page__title">护士提问</text>
		</view>
		
		<view v-if="loading" class="message-list-page__loading">
			<text class="message-list-page__loading-text">加载中...</text>
		</view>
		
		<view v-else-if="messageSessions.length === 0" class="message-list-page__empty">
			<text class="message-list-page__empty-text">暂无提问消息</text>
		</view>
		
		<view v-else class="message-list-page__list">
			<view 
				class="message-list-page__item" 
				v-for="(session, index) in messageSessions" 
				:key="session.senderId || index" 
				@click="() => handleOpenDetail(session)">
				<view class="message-list-page__avatar">
					<text class="message-list-page__avatar-text">{{ getAvatarText(session.senderName) }}</text>
				</view>
				<view class="message-list-page__info">
					<view class="message-list-page__header-row">
						<text class="message-list-page__name">{{ session.senderName }}</text>
						<text class="message-list-page__time">{{ formatTime(session.timestamp) }}</text>
					</view>
					<view class="message-list-page__preview">
						<text class="message-list-page__preview-text">{{ session.content || '暂无消息' }}</text>
						<view v-if="session.unreadCount > 0" class="message-list-page__badge">
							<text class="message-list-page__badge-text">{{ session.unreadCount > 99 ? '99+' : session.unreadCount }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getConversationList } from '@/api/secondVitim/message'

export default {
	data() {
		return {
			messageSessions: [],
			loading: false
		}
	},
	mounted() {
		this.loadSessions()
		// 监听消息更新事件
		uni.$on('message-updated', this.handleMessageUpdated)
	},
	beforeDestroy() {
		// 移除消息更新事件监听
		uni.$off('message-updated', this.handleMessageUpdated)
	},
	methods: {
		// 检查是否是护理组专家
		isExpert() {
			const userRoles = this.$store.state.user.roles || []
			return userRoles.some(role => {
				if (!role || typeof role !== 'string') {
					return false
				}
				const lowerRole = role.toLowerCase()
				return lowerRole === 'expert' || lowerRole.includes('expert')
			})
		},
		// 加载会话列表
		async loadSessions() {
			try {
				const userId = this.$store.state.user.id
				if (!userId) {
					console.warn('用户ID不存在，无法加载会话列表')
					this.messageSessions = []
					this.loading = false
					return
				}
				
				const res = await getConversationList(userId)
				console.log('会话列表API返回数据:', res)
				
				if (res && res.code === 200 && res.data) {
					let sessions = res.data;
					console.log('处理后的会话数据:', sessions)
					console.log('会话数量:', sessions.length)
					
					// 只显示发送给当前专家的消息（普通护士发送的提问）
					if (userId && sessions.length > 0) {
						sessions = sessions.filter(session => {
							if (!session) return false
							// 只显示接收者是当前专家的会话
							// 支持多种字段名：receiverId, receiver, receiver_id 等
							const receiverId = session.receiverId
							const match = receiverId == userId || receiverId === userId
							console.log('会话过滤:', {
								session: session,
								receiverId: receiverId,
								userId: userId,
								match: match
							})
							return match
						})
					}
					
					console.log('过滤后的会话数量:', sessions.length)
					// 按最后消息时间排序（支持单个或多个会话）
					this.messageSessions = sessions.sort((a, b) => {
						const timeA = this.parseTimestamp(a.timestamp)
						const timeB = this.parseTimestamp(b.timestamp)
						return timeB - timeA // 降序排列，最新的在前
					})
					
					console.log('最终会话列表:', this.messageSessions)
				} else {
					console.warn('API返回数据格式不正确:', res)
				}
			} catch (error) {
				console.error('加载会话列表失败:', error)
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				})
			}
		},
		// 解析时间戳字符串（支持 yyyy-mm-dd HH:mm:ss 格式）
		parseTimestamp(timestamp) {
			if (!timestamp) return 0
			
			// 如果已经是数字（时间戳），直接返回
			if (typeof timestamp === 'number') {
				return timestamp
			}
			
			// 处理字符串格式
			if (typeof timestamp === 'string') {
				// 替换中文冒号为英文冒号（处理可能的格式问题）
				let timeStr = timestamp.replace(/：/g, ':')
				
				// 处理 yyyy-mm-dd HH:mm:ss 格式
				// 将空格替换为 'T' 以便 Date 正确解析
				timeStr = timeStr.replace(' ', 'T')
				
				// 尝试解析日期
				const date = new Date(timeStr)
				
				// 检查日期是否有效
				if (isNaN(date.getTime())) {
					console.warn('无效的时间格式:', timestamp)
					return 0
				}
				
				return date.getTime()
			}
			
			return 0
		},
		// 获取头像文字
		getAvatarText(name) {
			if (!name) return '护'
			return name.charAt(0).toUpperCase()
		},
		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return ''
			// 使用 parseTimestamp 方法解析时间，支持 yyyy-mm-dd HH:mm:ss 格式
			const timestampValue = this.parseTimestamp(timestamp)
			if (timestampValue === 0) return ''
			
			const date = new Date(timestampValue)
			const now = new Date()
			const diff = now - date
			
			if (diff < 60000) {
				return '刚刚'
			} else if (diff < 3600000) {
				return Math.floor(diff / 60000) + '分钟前'
			} else if (diff < 86400000) {
				return Math.floor(diff / 3600000) + '小时前'
			} else if (diff < 604800000) {
				return Math.floor(diff / 86400000) + '天前'
			} else {
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				return `${month}-${day}`
			}
		},
		// 打开消息详情
		handleOpenDetail(session) {
			if (!session) {
				console.error('会话对象为空')
				return
			}
			console.log('打开消息详情，会话对象:', session)
			const senderId = session.senderId || session.id
			const senderName = session.senderName || session.name || '护士'
			if (!senderId) {
				console.error('发送者ID不存在')
				uni.showToast({
					title: '会话信息错误',
					icon: 'none'
				})
				return
			}
			uni.navigateTo({
				url: `/pages/mine/message/detail?sessionKey=${senderId}&nurseName=${encodeURIComponent(senderName)}`
			})
		},
		// 消息更新事件处理
		handleMessageUpdated() {
			this.loadSessions()
		}
	}
}
</script>

<style lang="scss" scoped>
.message-list-page {
	background-color: #f5f7fa;
	min-height: 100vh;
	
	&__header {
		background-color: #ffffff;
		padding: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #e8ecf0;
	}
	
	&__title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
	}
	
	&__loading {
		padding: 200rpx 0;
		text-align: center;
	}
	
	&__loading-text {
		font-size: 28rpx;
		color: #4a90e2;
	}
	
	&__empty {
		padding: 200rpx 0;
		text-align: center;
	}
	
	&__empty-text {
		font-size: 28rpx;
		color: #999999;
	}
	
	&__list {
		background-color: #ffffff;
		margin-top: 20rpx;
	}
	
	&__item {
		display: flex;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f2f5;
		background-color: #ffffff;
		transition: background-color 0.2s;
		
		&:active {
			background-color: #f5f7fa;
		}
	}
	
	&__avatar {
		width: 100rpx;
		height: 100rpx;
		background: linear-gradient(135deg, #4a90e2 0%, #67c23a 100%);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		flex-shrink: 0;
	}
	
	&__avatar-text {
		font-size: 36rpx;
		color: #ffffff;
		font-weight: bold;
	}
	
	&__info {
		flex: 1;
		min-width: 0;
	}
	
	&__header-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10rpx;
	}
	
	&__name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		flex: 1;
	}
	
	&__time {
		font-size: 24rpx;
		color: #999999;
		margin-left: 20rpx;
		flex-shrink: 0;
	}
	
	&__preview {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	&__preview-text {
		font-size: 28rpx;
		color: #666666;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	&__badge {
		background-color: #ff4757;
		border-radius: 20rpx;
		min-width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 12rpx;
		margin-left: 20rpx;
		flex-shrink: 0;
	}
	
	&__badge-text {
		font-size: 22rpx;
		color: #ffffff;
		font-weight: bold;
	}
}
</style>

